//
//  HttpRequestModel.m
//  爱启航
//
//  Created by 爱启航mac on 2017/7/24.
//  Copyright © 2017年 爱启航mac. All rights reserved.
//

#import "HttpRequestModel.h"

@implementation HttpRequestModel

static HttpRequestModel *_requestModel = nil;
+(HttpRequestModel *) sharedHttpRequestModel
{
    if (!_requestModel){
        _requestModel = [self init];
    }
    return _requestModel;
}

/**  请求 无进度 */
+ (void)httpRequest:(NSString *)urlString withParamters:(id)paramters isPost:(BOOL)isPost success:(void (^)(id responseData))success failure:(void (^)(NSError *error))failure {
    YYReachability *reachable = [[YYReachability alloc] init];
    if (reachable.status == YYReachabilityStatusNone) {
        [MBProgressHUD showMBPAlertView:@"请检查网络连接" withSecond:1.2];
        return;
    }
    [SVProgressHUD show];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setTimeoutInterval:10.f];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    [manager.requestSerializer setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    if (isPost) {
        
        [manager POST:urlString parameters:paramters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (success != nil) {
                success(responseObject);
                 [SVProgressHUD dismiss];
//                 [HttpRequestModel checkUserLoginState:responseObject];
            }
        }
              failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
                  if (failure != nil) {
                      failure(error);
                  }
                  BLLog(@"----failure---%@", error.description);
                   [SVProgressHUD dismiss];
              }];
        
    } else {
        [manager GET:urlString parameters:paramters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (success != nil) {
                success(responseObject);
                 [SVProgressHUD dismiss];
//                 [HttpRequestModel checkUserLoginState:responseObject];
            }
        }
             failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
                 if (failure != nil) {
                     failure(error);
                 }
 [SVProgressHUD dismiss];
             }];
    }
    
}

/** post 请求 无进度 */
+ (void)request:(NSString *)urlString withParamters:(NSDictionary *)dic success:(void (^)(id responseData))success failure:(void (^)(NSError *error))failure {
    YYReachability *reachable = [[YYReachability alloc] init];
    if (reachable.status == YYReachabilityStatusNone) {
        [MBProgressHUD showMBPAlertView:@"请检查网络连接" withSecond:1.2];
        return;
    }
    [SVProgressHUD show];
    [self printRequestUrlString:urlString withParamter:dic];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
//    manager.securityPolicy.allowInvalidCertificates = YES;
//    manager.securityPolicy.validatesDomainName = NO;
//    manager.requestSerializer.timeoutInterval = 15;
    NSSet *set = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/xml", @"text/plain", nil];
    manager.responseSerializer.acceptableContentTypes =[manager.responseSerializer.acceptableContentTypes setByAddingObjectsFromSet:set];
    [manager.requestSerializer setTimeoutInterval:10.f];
////    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
////    [manager.requestSerializer setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
//    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
////    [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
////    manager.responseSerializer = [AFJSONResponseSerializer serializer];//响应
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    
    NSMutableDictionary *finalDict = [NSMutableDictionary dictionaryWithDictionary:dic];
    [finalDict setObject:@"C00000070" forKey:@"channelId"];
 
    [manager POST:urlString parameters:finalDict headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success != nil){
            success(responseObject);
//            [HttpRequestModel checkUserLoginState:responseObject];
        }
           [SVProgressHUD dismiss];
    }
          failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
              BLLog(@"----failure---%@", error.description);
              if (failure != nil) {
                  failure(error);
              }
                 [SVProgressHUD dismiss];
          }];
}

/** Get 请求 无进度 */
+ (void)requestGet:(NSString *)urlString withParamters:(NSDictionary *)dic success:(void (^)(id responseData))success failure:(void (^)(NSError *error))failure {

    YYReachability *reachable = [[YYReachability alloc] init];
    if (reachable.status == YYReachabilityStatusNone) {
        [MBProgressHUD showMBPAlertView:@"请检查网络连接" withSecond:1.2];
        return;
    }
    [SVProgressHUD show];
    [self printRequestUrlString:urlString withParamter:dic];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setTimeoutInterval:10.f];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    [manager.requestSerializer setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//响应
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    [manager GET:urlString parameters:dic headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success != nil) {
            success(responseObject);
//            [HttpRequestModel checkUserLoginState:responseObject];
        }
           [SVProgressHUD dismiss];
        
    }
         failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
             BLLog(@"----failure---%@", error.description);
             if (failure != nil) {
                 failure(error);
             }
             [SVProgressHUD dismiss];
         }];
    
}


//+(void)checkUserLoginState:(NSDictionary *)responseData{
//    if ([responseData[@"status"] integerValue]==888) {
//        NSDictionary *dic = @{@"username":USERNAME,
//                              @"password":[userDefault objectForKey:@"password"]};
//        [HttpRequestModel request:[HTTPInterface loginAccount] withParamters:dic success:^(id responseData) {
//            NSLog(@"重新登录:%@",responseData);
//        } failure:^(NSError *error) {
//        }];
//    }
//}



+ (void)printRequestUrlString:(NSString *)urlString withParamter:(NSDictionary *)dic {
    /*
    if ([USERID length]!=0) {
        //获取cookie
        NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage]cookiesForURL:[NSURL URLWithString:urlString]];
        for (NSHTTPCookie *cookie in cookies)
        {
            //打印cookies
            //NSLog(@"getCookie:%@",tempCookie);
            if ([cookie.name isEqualToString:@"JSESSIONID"]) {
                NSNumber *sessionOnly = [NSNumber numberWithBool:cookie.sessionOnly];
                NSNumber *isSecure = [NSNumber numberWithBool:cookie.isSecure];
                
                NSArray *cookies = [NSArray arrayWithObjects:cookie.name, cookie.value, sessionOnly, cookie.domain, cookie.path, isSecure, nil];
                [userDefault setObject:cookies forKey:@"cookieLM"];
                [userDefault synchronize];
                break;
            }
        }
    }
    */
    
    NSArray *dicKeysArray = [dic allKeys];
    NSString *urlWithParamterString = urlString;
    if (dicKeysArray.count != 0) {
        urlWithParamterString = [urlWithParamterString stringByAppendingString:@"?"];
    }
    for (NSInteger i = 0; i < dicKeysArray.count; i++) {
        urlWithParamterString = [urlWithParamterString stringByAppendingString:[NSString stringWithFormat:@"%@=%@&", dicKeysArray[i], [dic objectForKey:dicKeysArray[i]]]];
        if (i == dicKeysArray.count - 1) {
            urlWithParamterString = [urlWithParamterString substringToIndex:urlWithParamterString.length - 1];
        }
    }
    BLLog(@"\n\n路径--%@", urlWithParamterString);
}

@end
